package structures.stack;

import java.util.Scanner;

public class LinkStackDemo {
    public static void main(String[] args) {
        LinkStack linkStack = new LinkStack();

        char key = ' ';
        Scanner scanner = new Scanner(System.in);
        boolean loop = true;
        while (loop) {
            System.out.println();
            System.out.println("s(show) 显示全部数据");
            System.out.println("e(exit) 退出程序");
            System.out.println("a(add) 添加数据");
            System.out.println("g(get) 获取数据");
            key = scanner.next().charAt(0);
            switch (key) {
                case 's':
                    linkStack.show();
                    break;
                case 'e':
                    scanner.close();
                    loop = false;
                    break;
                case 'a':
                    int data = scanner.nextInt();
                    linkStack.push(data);
                    break;
                case 'g':
                    System.out.println(linkStack.pop());
                    break;
            }
            System.out.println("------------------------");
        }
    }
}

class LinkStack {
    private StackNode headNode = new StackNode(0);

    public StackNode getHeadNode() {
        return headNode;
    }

    public Boolean isEmpty() {
        StackNode headNode = getHeadNode();
        return headNode.getNext() == null;
    }

    public void push(int data) {
        StackNode newNode = new StackNode(data);
        StackNode node = getHeadNode();
        while (node.getNext() != null) {
            node = node.getNext();
        }
        node.setNext(newNode);
    }

    public int pop() {
        if (isEmpty()) throw new RuntimeException("栈为空..没有数据");
        StackNode node = getHeadNode().getNext();
        StackNode preNode = getHeadNode();
        while (node.getNext() != null) {
            preNode = node;
            node = node.getNext();
        }
        preNode.setNext(null);
        return node.getData();
    }

    public void show() {
        StackNode node = getHeadNode();
        while (node.getNext() != null) {
            node = node.getNext();
            System.out.print(node.getData() + "\t");
        }
        System.out.println("--显示完毕--");
    }
}

class StackNode {
    private StackNode next;
    private int data;

    public StackNode(int data) {
        this.data = data;
    }

    public StackNode getNext() {
        return next;
    }

    public void setNext(StackNode next) {
        this.next = next;
    }

    public int getData() {
        return data;
    }

    public void setData(int data) {
        this.data = data;
    }
}
